<?php
/**
 * description...
 *
 * @author Tinyhu
 * @package SimpleController
 */
class SimpleController extends Controller{

    public $layout='simple';
    public $safebox = null;
    private $user;
    private $model = null;
    //private $cookie_time = 31622400;
    private $cookie_time = 0;
    private $cart = array();

    public function init(){
        header("Content-type: text/html; charset=".$this->encoding);
        $this->model = new Model();
        $this->safebox =  Safebox::getInstance();
        $this->user = $this->safebox->get('user');
        if($this->user==null){
            $this->user = Common::autoLoginUserInfo();
            $this->safebox->set('user',$this->user);
        }
        $config = Config::getInstance();
        $site_config = $config->get("globals");
        $this->assign('seo_title',$site_config['site_name']);
        $this->assign('site_title',$site_config['site_name']);
        $this->assign('site_url',$site_config['site_url']);
        
        $cart = Cart::getCart();
        $this->cart = $cart->all();
        $this->assign("cart",$this->cart);
    }
        
    public function reg()
    {   $this->redirect('login');die;
        $num = strval(Filter::sql(Filter::text(Req::args("num"))));
        
        if(!empty($num))
        {
            $this->assign('tjr_number', $num);
            /*
            $model = new Model();
            $obj = $model->query("select id from zyk_user where number='$num';");
            
            if(!empty($obj))
            {
                $this->assign('tjr_number', $num);
            }
            */
        }
        
        $this->layout = '';
        $this->redirect();
    }
		/**
	     * 用户注册
	     * Enter description here ...
	     */
		public function reg_act(){
//            print_r(Req::post());die;
        if($this->getModule()->checkToken('reg'))
        {
            $tjr_name = Filter::sql(Req::args('tjr_name'));//推荐人
            $uname = Filter::sql(Req::post('uname'));//用户名
            /*
            $t_name = Filter::sql(Req::args('t_name'));
            $jd_name = Filter::sql(Req::args('jd_name'));
            */
            $passWord = Req::post('password');//登录密码
            $passwordtwo = Req::args('passwordtwo');//支付密码
            $agent = Req::args('agent');//投资级别
            $province = Req::args('province');//省
            $city = Req::args('city');//市
            $county = Req::args('county');//县

//            $validate_code = Req::args('validate_code');//短信验证码
            
            //$rePassWord = Req::post('repassword');
            /*
            $this->safebox = Safebox::getInstance();
            $code = $this->safebox->get($this->captchaKey);
            $verifyCode = Req::args("verifyCode");//验证码
            $checkFlag  = ($verifyCode==$code);
            */
            //$info       = array('field'=>'verifyCode','msg'=>'验证码错误!');
            
            
//             if($checkFlag)
//             {    


                $model = new Model();

                //判断推荐人是否存在

                if(empty($tjr_name))
                {
                    //$tjr_id = 0;
                    $info = array('field'=>'tjr_name','msg'=>"推荐人不能为空");
                    $this->assign("invalid",$info);
                    $this->redirect("reg",false,Req::args());
                    die;
                }
                else 
                {
//                    $number = strval(trim($tjr_name));
                    //推荐编码为手机号或者编码都行
//                    $tjr_obj = $model->query("select * from zyk_user where number='{$number}' or name='{$number}';");
//                    $tjr_obj = $tjr_obj[0];
                    $tjr_obj = $model->table('user')->where("name='$tjr_name'")->find();

                    if(empty($tjr_obj))
                    {
                        $info = array('field'=>'tjr_name','msg'=>"您输入的推荐人不存在");
                        $this->assign("invalid",$info);
                        $this->redirect("reg",false,Req::args());
                        die;
                    }
                    else
                    {
                        $tjr_id = intval($tjr_obj['id']);
                    }
                }

            //判断用户名
            if(empty($uname))
            {
                $info = array('field'=>'uname','msg'=>"用户名不能为空");
                $this->assign("invalid",$info);
                $this->redirect("reg",false,Req::args());
                die;
            }
            else
            {
                //判断用户名是否存在
                $sql = "select * from zyk_user where name='{$uname}'";
                if(Common::check_is_exists_of_talbe($sql))
                {
                    $info = array('field'=>'uname','msg'=>"您输入的用户名已存在");
                    $this->assign("invalid",$info);
                    $this->redirect("reg",false,Req::args());
                    die;
                }
            }

                
                if(strlen($passWord)<6 || strlen($passwordtwo)<6)
                {
                    $info = array('field'=>'password','msg'=>'密码长度必需大于等于6位！');
                    $this->assign("invalid",$info);
                    $this->redirect("reg",false,Req::args());
                    die;
                }

            //判断代理类别是否存在
            if(empty($agent))
            {
                $info = array('field'=>'agent','msg'=>"请选择投资级别");
                $this->assign("invalid",$info);
                $this->redirect("reg",false,Req::args());
                die;
            }
            else
            {
                if ($agent == 3) {//判断县代是否存在
                    if (!$county || !$city || !$province) {//至少有一个不存在
                        $info = array('field'=>'county','msg'=>"县代必须选择区域");
                        $this->assign("invalid",$info);
                        $this->redirect("reg", false, Req::args());
                        die;
                    }
                    $dl_area = $province.','.$city.','.$county;
                    if(Common::check_area_exist($dl_area)){
                        $info = array('field'=>'county','msg'=>"该区域已经被占领请更换其他区域");
                        $this->assign("invalid",$info);
                        $this->redirect("reg", false, Req::args());
                        die;
                    }
                }

                if ($agent == 4) {
                    if (!$city || !$province) {//至少有一个不存在
                        $info = array('field'=>'county','msg'=>"市代必须选择区域");
                        $this->assign("invalid",$info);
                        $this->redirect("reg", false, Req::args());
                        die;
                    }
                    $dl_area = $province.','.$city;
                    if(Common::check_area_exist($dl_area)){
                        $info = array('field'=>'county','msg'=>"该区域已经被占领请更换其他区域");
                        $this->assign("invalid",$info);
                        $this->redirect("reg", false, Req::args());
                        die;
                    }
                }

            }
                //判断短信验证码是否正确
//                $sms_code_obj = $model->table("sms_code")->where("mobile='{$uname}' and sms_code='{$validate_code}' and sms_is_used=0")->find();
//                if(empty($sms_code_obj))
//                {
//                    $info = array('field'=>'validate_code','msg'=>"手机短信验证码不正确");
//                    $this->assign("invalid",$info);
//                    $this->redirect("reg",false,Req::args());
//                    die;
//                }
//                else
//                {
//                    if(strtotime($sms_code_obj['sms_close_time']) < time())
//                    {
//                        $info = array('field'=>'validate_code','msg'=>"验证码已过期，请重新获取");
//                        $this->assign("invalid",$info);
//                        $this->redirect("reg",false,Req::args());
//                        die;
//                    }
//                }
                
                $model->query("START TRANSACTION");
                
                $validcode = CHash::random(8);
                $pass      = CHash::md5($passWord,$validcode);
                
                //向user表中插入数据
                $last_id = $model->table('user')->data(array('name'=>$uname,'tjr_id'=>$tjr_id,'password'=>$pass,'passwordtwo'=>CHash::md5($passwordtwo),'pass1'=>$passWord,'pass2'=>$passwordtwo,'validcode'=>$validcode,'status'=>1))->insert();
//                print_r($last_id);die;
//                $new_number = Common::create_number($uname);
                //$new_number = substr($uname,-6);
                
//                $result1    = $model->table("user")->data(['number'=>$new_number])->where("id=$last_id")->update();
               
                //推荐人直推人数加1
                if($tjr_id > 0)
                {
                    $result2 = $model->table("user")->data(['u_tjrs'=>"`u_tjrs`+1"])->where("id=".$tjr_id)->update();
                    if(!$result2)
                    {
                        $model->query("rollback");
                        $info = array('field'=>'validate_code','msg'=>"注册失败，请重新操作");
                        $this->assign("invalid",$info);
                        $this->redirect("reg",false,Req::args());
                        die;
                    }
                }
                $now_date    = date('Y-m-d H:i:s',time());
                $result5 = $model->table('grade')->where('id='.$agent)->find();
                $gwjf = $result5['money'];//购物积分
                $zc = Common::get_zc_limit($result5);//资产
                $last_fhjf = $result5['money']*Common::getConfig('jjset_fhjLimit');//剩余分红积分

                //$result3 = $model->table("customer")->data(array('user_id'=>$last_id,'reg_time'=>$now_date))->insert();
//                $result3 = $model->query("insert into zyk_customer (user_id,group_id,dl_area,gwjf,zc,last_fhjf,reg_time)values($last_id,$agent,$dl_area,$gwjf,$zc,$last_fhjf,$now_date)");
//                 var_dump($result3);die;
                $mx = [
                    'user_id'=>$last_id,'group_id'=>$agent,'reg_time'=>$now_date,
                    'gwjf'=>$gwjf,'zc'=>$zc,'last_fhjf'=>$last_fhjf,'dl_area'=>$dl_area
                ];
//
                $result3 = $model->table('customer')->data($mx)->insert();
                //修改短信验证码状态
//                $result4 = $model->table("sms_code")->data(['sms_is_used'=>1])->where("id=".$sms_code_obj['id'])->update();
//                var_dump($result3);die;

//            var_dump($res);die;
                //if($result1 && $result2 && $result3 && $result4)
                if( $result2 && $result3==0)
                {
                    $model->query("COMMIT");
                    if( $tjr_id > 0 )
                    {
                        //添加子孙链
                        Common::addChildLink($last_id, $tjr_obj['id']);
                    }
                    //赠送推广额度
//                    Jjjs::reg_zs_extend_je($last_id);
                }
                else
                {
                    $model->query("ROLLBACK");
                    //$url=Url::createUrl("/simple/reg");
                    //echo "<script>alert('注册失败,请重新操作');document.location.href='$url';</script>";

                    $info = array('field'=>'validate_code','msg'=>"注册失败，请重新操作");
                    $this->assign("invalid",$info);
                    $this->redirect("reg",false,Req::args());
                    die;
                }
                //记录登录信息
                $obj = $model->table("user as us")->join("inner join customer as cu on us.id = cu.user_id")->fields("us.*,cu.login_time")->where("us.name='$uname'")->find();
                //$this->safebox->set('user',$obj,1800);
                $this->safebox->set('user',$obj);
                

                //$args = array("t_name"=>$t_name,'user_name'=>$uname);
                $args = array("t_name"=>$tjr_obj['name'],'user_name'=>$uname);
                $this->redirect("reg_result",true,$args);
                
            //}
        }
        else
        {
            $this->redirect("/index/msg",false,array('type'=>"fail","msg"=>'注册无效',"content"=>"非法进入注册页面！","redirect"=>"/simple/reg"));
            exit();
        }
            $info = array('field'=>'validate_code','msg'=>"注册失败，请重新操作");
            $this->assign("invalid",$info);
            $this->redirect("reg",false,Req::args());
    }
    
    
    
    /**
     * 获取注册短信验证码
     */
    public function sms_send()
    {
        $status = Common::getConfigJjsetValue("jjset_sms_send");
        if(intval($status) !== 0)
        {
            $mobile = Filter::text(Req::args("mobile"));//手机号码
    
            $model        = new Model();
            $sms_code_obj = $model->table("sms_code")->where("mobile='{$mobile}' and sms_is_used=0")->order("id desc")->select();
            $sms_code_obj = $sms_code_obj[0];
            if( empty($sms_code_obj) )//找回密码短信
            {
                self::send_and_save_msg($mobile);
                echo "短信已发送到您的手机，请注意查收,有效期为5分钟!";
            }
            else
            {
                //如果验证码已经发送，并且还在有效期内，则不在发送短信
                if(strtotime($sms_code_obj['sms_close_time']) > time())
                {
                    echo '您的操作太频繁，请在5分钟之后点击获取短信验证码';
                    die;
                }
                else
                {
                    //验证码过期
                    $model->table("sms_code")->data(['sms_is_used'=>1])->where("id=".$sms_code_obj['id'])->update();
                    self::send_and_save_msg($mobile);
                    echo "短信已发送到您的手机，请注意查收,有效期为5分钟!";
                }
            }
        }
        else
        {
            echo "短信服务平台正在维护，请稍后";
            die;
        }
    }
    
    
    /**
     * 发送和保存短信
     */
    static function send_and_save_msg($mobile)
    {
        $model = new Model();
        //发送短信
        $str = "0123456789";
        //截取6位数字的验证码
        $new_str = substr(str_shuffle($str),0,6);
        $arr['code'] = $new_str;
    
        Sms::send(6, $mobile, $arr);
    
    
        //生成短信记录
        $data['mobile']   = $mobile;
        $data['sms_code'] = $new_str;
        $data['sms_close_time'] = date("Y-m-d H:i:s",strtotime("+5 minute"));
        $data['sms_is_used'] = 0;
        $model->table("sms_code")->data($data)->insert();
    }
    
    
    
    
    //账户激活邮件认证
    public function activation_user()
    {
        $code =Filter::text(Req::args('code'));
        $email_code = urldecode(substr($code,32));
        $valid_code = substr($code,0,32);
        $email = Crypt::decode($email_code);
        if(Validator::email($email)){
            $model = new Model('user');
            $user = $model->where("email='".$email."'")->find();

            if($user && $user['status']==0 && md5($user['validcode'])==$valid_code){
                $model->data(array('status'=>1))->where('id='.$user['id'])->update();
                $this->redirect("/index/msg",false,array('type'=>"success","msg"=>'账户激活成功',"content"=>"账户通过邮件成功激活。","redirect"=>"/simple/login"));
                exit();
            }
        }
        $this->redirect("/index/msg",false,array('type'=>"fail","msg"=>'账户激活失败',"content"=>"你的连接地址无效，无法进行账户激活，请核实你的连接地址无误。"));

    }
    
    public function test()
    {
        ;

        $father_cate = [];
//        $father = $model ->table('goods_category')->where("id= 63")->find();

       $res =  $this->getAll(63,$father_cate);
        var_dump($res);
    }

    public function getAll($id,$father_cate)
    {
        $model = new Model();
        $fathers = $model ->table('goods_category')->where("parent_id= $id")->findAll();
        $cate = array();
        foreach($fathers as $father){

            $cate['name'] =$father['name'];
            $cate['img'] =$father['img'];
            $cate['sort'] =$father['sort'];

            $sons = $model ->table('goods_category')->where("parent_id= {$father['id']}")->findAll();
            if(empty($sons))
            {
                $cate['childs']=$this->getAll($father['id'],$father_cate);
            }else{

                $cate['childs']="";
            }
            array_push($father_cate,$cate);

        }

        return $father_cate;
    }


    public function login()
    {
        $this->layout = '';
        if($this->checkOnline())
            $this->redirect('/ucenter/index');
        else {
            $model = new Model('oauth');
            $oauths = $model->where('status = 1 order by `sort` desc')->findAll();
            $oauth_login = array();
            foreach ($oauths as $oauth) {
               $tem = new $oauth['class_name']();
               $oauth_login[$oauth['name']]['url'] = $tem->getRequestCodeURL();
               $oauth_login[$oauth['name']]['icon'] = $oauth['icon'];
            }
            $this->assign('oauth_login',$oauth_login);
            $this->redirect();
        }
    }
    

    //从后台直接进入个人中心    
    //从后台直接进入个人中心
    public function pt_login_act(){
        // Filter::form();
        $model = $this->model->table("user");
        $user_id = Filter::int(Req::args("user_id"));
        $obj = $model->where("id=$user_id")->find();

        // echo $user_id;exit;
        $name = $obj['name'];
        // $password = $obj['pass1'];
        $validcode = $obj['validcode'];


        if($obj){

            //Common::auto_dong_account($user_id);


            // if($obj['status']==1){
            // if($obj['password'] == CHash::md5($password,$validcode)){
            $cookie = new Cookie();
            $cookie->setSafeCode(Tiny::app()->getSafeCode());
            if($autologin==1) {
                $this->safebox->set('user',$obj,$this->cookie_time);

                // $cookie->set('autologin',array('name'=>$name,'password'=>$obj['password']),$this->cookie_time);
                $cookie->set('autologin',array('name'=>$name,'password'=>md5($validcode)),$this->cookie_time);
            }
            else {
                $cookie->set('autologin',null,0);
                $this->safebox->set('user',$obj, 1800);

            }
            // $this->model->table("user")->data(array('login_time'=>date('Y-m-d H:i:s')))->where('id='.$obj['id'])->update();

            $this->redirect('/ucenter/index');

            exit;
            // }else{
            //     $info = array('field'=>'password','msg'=>'密码错误！');
            // }
            // }else if($obj['status']==2){
            //     $info = array('field'=>'name','msg'=>'账号已经锁定！');
            // }else{
            //     $info = array('field'=>'name','msg'=>'账号还未激活！');
            // }

        }else{
            $info = array('field'=>'name','msg'=>'账号不存在！');
        }

        $this->assign("invalid",$info);
        $this->redirect("login",false,Req::args());
    }
    
    
    
    public function login_act(){
        
//         $info = array('field'=>'valicode', 'msg'=>'暂时无法登录');
//         $this->assign("invalid",$info);
//         $this->redirect("login",false,Req::args());
//         die;
        
        
        $redirectURL = Req::args("redirectURL");
        $this->assign("redirectURL",$redirectURL);
        
        $account = Filter::sql(Req::post('account'));
        $passWord = Filter::text(Req::post('password'));
        
        
        //验证验证码
        $this->safebox = Safebox::getInstance();
        $code = $this->safebox->get($this->captchaKey);
        $verifyCode = strval(Req::args("valicode"));//验证码
        $checkFlag  = ($verifyCode === strval($code));
        
        if($checkFlag)
        {
            $autologin = Req::args("autologin");
            if($autologin==null)$autologin = 0;
            $model = $this->model->table("user as us");
            $obj = $model->join("inner join customer as cu on us.id = cu.user_id")->fields("us.*,cu.group_id,cu.user_id,cu.login_time,cu.mobile")->where("us.name='$account'")->find();
            if($obj)
            {
                if($obj['status']==1){
                    if($obj['password'] == CHash::md5($passWord,$obj['validcode'])){
                        $cookie = new Cookie();
                        $cookie->setSafeCode(Tiny::app()->getSafeCode());
                        /*
                        if($autologin==1) {
                            $this->safebox->set('user',$obj,$this->cookie_time);
    
                            $cookie->set('autologin',array('account'=>$account,'password'=>$obj['password']),$this->cookie_time);
                        }
                        else {
                            $cookie->set('autologin',null,0);
                            $this->safebox->set('user',$obj, 1800);
    
                        }
                        */
                        $this->safebox->set('user',$obj);
                        $this->model->table("customer")->data(array('login_time'=>date('Y-m-d H:i:s')))->where('user_id='.$obj['id'])->update();
                        $redirectURL = Req::args("redirectURL");
    
                        if($redirectURL!='' && preg_match("/https?:\/\//i",$redirectURL)==0 && stripos($redirectURL, "reg")===false && stripos($redirectURL, "login_act")===false&& stripos($redirectURL, "oauth_bind")===false&& stripos($redirectURL, "activation_user")===false && stripos($redirectURL, "reset_password_act")===false)
                                header('Location: '.$redirectURL, true, 302);
                        else 
                            $this->redirect('/index/index');
                        exit;
                    }else{
                        $info = array('field'=>'password','msg'=>'用户名或密码错误！');
                    }
                }else if($obj['status']==2){
                    $info = array('field'=>'account','msg'=>'账号已经锁定，请联系管理人员！');
                }else{
                    $info = array('field'=>'account','msg'=>'账号还未激活，无法登录！');
                }
    
            }
            else
            {
                $info = array('field'=>'account','msg'=>'账号不存在！');
            }   
        }
        else 
        {
            $info = array('field'=>'valicode', 'msg'=>'验证码不正确');
        }
        $info['account'] = $account;
        $this->assign("invalid",$info);

        if(!empty($info))
        {
            //如果登录出现异常，则清空cooki和session
            $this->safebox->clear('user');
            $cookie = new Cookie();
            $cookie->setSafeCode(Tiny::app()->getSafeCode());
            $cookie->set('autologin',null,0);
        }
        
        $this->redirect("login",false,Req::args());
    }
    
    
    public function forget_act(){

        $account =  Filter::sql(Req::args('account'));
        $verifyCode =  Filter::sql(Req::args('verifyCode'));
        $this->safebox = Safebox::getInstance();
        $code = $this->safebox->get($this->captchaKey);
        if($code != $verifyCode) $this->redirect('forget_password',false);
        if(Validator::email($account)){
            $email = $account;
            $model = $this->model->table('user');
            $obj = $model->where("email = '".$email."'")->find();
            if(!empty($obj)){
                $model = $this->model->table('reset_password');
                $obj = $model->where("email = '".$email."'")->find();
                $safecode = md5(md5($email).md5(CHash::random(32)));
                if(!empty($obj)){
                    $obj['safecode'] = $safecode;
                    $model->data($obj)->update();
                }
                else{
                    $model->data(array('email'=>$email,'safecode'=>$safecode))->add();
                }
                $reset_url = Url::fullUrlFormat("/simple/reset_password/safecode/$safecode");
                $msg_content = '';
                $site_url = Url::fullUrlFormat('/');
                $msg_title = '找回密码--'.$this->site_name;

                $msg_template_model = new Model("msg_template");
                $msg_template = $msg_template_model->where('id=3')->find();
                if($msg_template){
                    $msg_content = str_replace(array('{$site_name}','{$reset_url}','{$site_url}','{$current_time}'), array($this->site_name,$reset_url,$site_url,date('Y-m-d H:i:s')), $msg_template['content']);
                    $msg_title = $msg_template['title'];
                }else{
                    $msg_content .='<p>亲爱的用户:</p>';
                    $msg_content .='<p>感谢您注册'.$this->site_name.',请点击以下链接重置您的密码。<br/><br/>';
                    $msg_content .="<a href='{$reset_url}' target='_blank'>{$reset_url}</a><br/><br/>";
                    $msg_content .='愿您在'.$this->site_name.'度过愉快的时光。<br/><br/>';
                    $msg_content .="<a href='".$site_url."'>".$this->site_name."</a></p>";
                }
                $mail = new Mail();
                $flag = $mail->send_email($email,$msg_title,$msg_content);
                if($flag){
                    $this->assign('status','success');
                }
                else{
                    $this->assign('status','error');
                }
            }else{
                $this->assign('status','fail');
            }
            $this->assign('accountType','email');
            $this->redirect('forget_result',false);
        }elseif(Validator::mobi($account)){
            $mobile = $account;
            $model = $this->model->table('customer');
            $obj = $model->where("mobile = '".$mobile."'")->find();
            $this->assign('accountType','mobile');
            if(!empty($obj)){

                $sms = SMS::getInstance();
                if($sms->getStatus()){
                    $code = CHash::random('6','int');
                    $result = $sms->sendCode($mobile,$code);
                    if($result['status']=='success')
                    {
                        $model = $this->model->table('reset_password');
                        $model->data(array('email'=>$mobile,'safecode'=>$code))->insert();
                        $this->assign('status','success');
                    }else{
                        $this->assign('status','error');
                    }
                }else{
                    $this->assign('status','fail');
                }
                $this->redirect('forget_result',false);
            }else{
                $this->redirect('forget_password',false);
            }

        }else{
            $this->redirect('forget_password',false);
        }

    }
    public function reset_password()
    {
        $safecode = Filter::sql(Req::args('safecode'));
        if($safecode!=null && (strlen($safecode)==32 || strlen($safecode)==6))
        {
            $model = $this->model->table('reset_password');
            $obj = $model->where("safecode='".$safecode."'")->find();
            $this->assign('status','fail');
            $this->assign('safecode',$safecode);
            if(!empty($obj)) $this->assign('status','success');
            $this->redirect();
        }
        else
        {
            $this->redirect('index/index');
        }
    }
    public function reset_password_act(){
        $safecode = Filter::sql(Req::args('safecode'));
        $password = Req::args('password');
        $repassword = Req::args('repassword');
        if($password == $repassword)
        {
            $model = new Model('reset_password');
            $obj = $model->where("safecode='".$safecode."'")->find();
            if(!empty($obj))
            {
                $validcode = CHash::random(8);
                if(strlen($safecode)==32){
                    $umodel = $this->model->table('user');
                    $umodel->where("email='".Filter::sql($obj['email'])."'")->data(array('password'=>CHash::md5($password,$validcode),'validcode'=>$validcode))->update();
                }else{
                    $cumodel = $this->model->table('customer');
                    $mobile = $obj['email'];
                    $cuobj = $cumodel->where("mobile='$mobile'")->find();
                    $umodel = $this->model->table('user');
                    $umodel->where("id=".$cuobj['user_id']."")->data(array('password'=>CHash::md5($password,$validcode),'validcode'=>$validcode))->update();
                }
                $model->where('id='.$obj['id'])->delete();
                $this->assign('status','success');
                $this->redirect('reset_result',false);
            }
            else
            {
                $this->assign('status','fail');
                $this->redirect('reset_result',false);
            }
        }
        else
        {
            $this->assign("invalid",array('field'=>'repassword','msg'=>'两次密码不一致！'));
            $this->redirect('reset_password',false,Req::args());
        }
    }
    /**
     * 第三方登录回调地址,跳转到绑定到用户页面。
     * @return void
     */
    function callback(){

        $type = Filter::sql(Req::args('type'));
        $code = Filter::sql(Req::args('code'));
        (empty($type) || empty($code)) && die('参数错误');

        $oauth = new $type();

        //腾讯微博需传递的额外参数
        $extend = null;
        if($type == 'tencent'){
            $extend = array('openid' => $this->_get('openid'), 'openkey' => $this->_get('openkey'));
        }

        $token = $oauth->getAccessToken($code , $extend);
        $userinfo = $oauth->getUserInfo();
        if(!empty($userinfo)){
            $oauth_user = $this->model->table('oauth_user');
            $is_oauth = $oauth_user->fields('user_id')
                ->where('open_id="'.$token['openid'].'" and oauth_type="'.$type.'"')
                ->find();
            if($is_oauth){
                //已绑定用户
                if($is_oauth['user_id']>0){
                    $obj = $this->model->table("user as us")->join("left join customer as cu on us.id = cu.user_id")->fields("us.*,cu.group_id,cu.login_time")->where("us.id='{$is_oauth['user_id']}'")->find();
                    $this->safebox->set('user',$obj, $this->cookie_time);
                    $this->redirect('/ucenter/index');
                    exit();
                }
            }else{
                $oauth_user->data(array(
                        'open_name'=>$userinfo['open_name'],
                        'oauth_type' => $type,
                        'posttime'=>time(),
                        'token' =>$token['access_token'],
                        'expires'=>$token['expires_in'],
                        'open_id'=>$token['openid']
                    ))->insert();
            }
            $oauth_info = $oauth->getConfig();
            $userinfo['type_name'] = $oauth_info['name'];
            $userinfo['open_id'] = $token['openid'];
            $userinfo['oauth_type'] = $type;
            Session::set('oauth_user_info',$userinfo);
            $this->redirect("/simple/oauth_bind");
        }
    }
    /**
     * 用户绑定Action
     * @return
     */
    public function oauth_bind()
    {
        $userinfo = Session::get('oauth_user_info');
        if($userinfo){
            $this->assign('type_name',$userinfo['type_name']);
            $this->assign('open_name',$userinfo['open_name']);
            $this->assign('head_img',$userinfo['head']);
            $this->assign("user",$this->user);
            $this->redirect("/simple/oauth_bind");
        }
        else{
            $this->redirect("/index/index");
        }
    }
    /**
     * 绑定用户Action
     */
    public function oauth_bind_act()
    {
        $userinfo = Session::get('oauth_user_info');

        if($userinfo){
            $account = Filter::sql(Req::args('account'));
            $passWord = Req::post('password');
            $rePassWord = Req::post('repassword');

            if(strlen($passWord)<6){
                $info = array('field'=>'password','msg'=>'密码长度必需大于6位！');
            }else{
                $info = null;
                $model = $this->model->table("user as us");
                $obj = $model->join("left join customer as cu on us.id = cu.user_id")->fields("us.*,cu.group_id,cu.user_id,cu.login_time,cu.mobile")->where("us.email='$account' or us.name='$account' or cu.mobile='$account'")->find();
                if($obj){
                    if($obj['password'] == CHash::md5($passWord,$obj['validcode'])){
                        $test = $this->model->table('oauth_user')->where("oauth_type='{$userinfo['oauth_type']}' and open_id='{$userinfo['open_id']}'")->data(array('user_id'=>$obj['id']))->update();
                        $this->safebox->set('user',$obj,1800);
                        $this->redirect("/ucenter/index");
                        exit;
                    }else{
                        $info = array('field'=>'password','msg'=>'密码与用户名是不匹配的，无法绑定!');
                    }
                }else{

                    if($passWord == $rePassWord){
                        if(Validator::email($account)){
                            $email = $account;
                            $mobile = '';
                        }elseif(Validator::mobi($account)){
                            $mobile = $account;
                            $email  = $mobile.'@no.com';
                        }
                        $model = $this->model->table("user");
                        $validcode = CHash::random(8);
                        $last_id = $model->data(array('email'=>$email,'name'=>$userinfo['open_name'],'password'=>CHash::md5($passWord,$validcode),'validcode'=>$validcode))->insert();
                        $time = date('Y-m-d H:i:s');
                        $model->table("customer")->data(array('user_id'=>$last_id ,'reg_time'=>$time,'login_time'=>$time,'mobile'=>$mobile))->insert();
                        //记录登录信息
                        $obj = $model->table("user as us")->join("left join customer as cu on us.id = cu.user_id")->fields("us.*,cu.group_id,cu.login_time,cu.mobile")->where("us.email='$account' or cu.mobile='$account'")->find();
                        $this->safebox->set('user',$obj,1800);
                        $this->model->table('oauth_user')->where("oauth_type='{$userinfo['oauth_type']}' and open_id='{$userinfo['open_id']}'")->data(array('user_id'=>$last_id))->update();
                        $this->redirect("/ucenter/index");
                        exit;
                    }
                    else{
                        $info = array('field'=>'repassword','msg'=>'两次密码输入不一致！');
                    }
                }
            }
            $this->assign("invalid",$info);
            $this->redirect("/simple/oauth_bind",false,Req::args());
        }
        else{
            $this->redirect("/index/index");
        }
    }

    public function cart()
    {
        $type = Req::args('cart_type');
        $this->assign("cart_type","cart");
        if($type=='goods'){
            $cart = Cart::getCart('goods');
            $this->cart = $cart->all();
            $this->assign("cart_type","goods");
            $this->assign("cart",$this->cart);
        }
        $this->redirect();
    }

    public function order(){
        $type = Req::args('cart_type');
        if($type=='goods'){
            $cart = Cart::getCart('goods');
            $this->cart = $cart->all();
            $this->assign('cart',$this->cart);
            $this->assign('cart_type','goods');
        }
        if(!$this->cart)$this->redirect("cart");
        if($this->checkOnline()){
            $this->parserOrder();
            $this->redirect();
        }else{
            $this->redirect("login");
        }
    }
    //解析订单
    private function parserOrder(){
        $config = Config::getInstance();
        $config_other = $config->get('other');
        $open_invoice = isset($config_other['other_is_invoice'])?!!$config_other['other_is_invoice']:false;
        $tax = isset($config_other['other_tax'])?intval($config_other['other_tax']):0;

        $area_ids = array();
        $address = $this->model->table("address")->where("user_id=".$this->user['id'])->order("is_default desc")->findAll();
        foreach ($address as $add) {
            $area_ids[$add['province']] = $add['province'];
            $area_ids[$add['city']] = $add['city'];
            $area_ids[$add['county']] = $add['county'];
        }
        $area_ids = implode(",",$area_ids);
        $areas = array();
        if($area_ids!='')$areas = $this->model->table("area")->where("id in($area_ids )")->findAll();
        $parse_area = array();
        foreach ($areas as $area) {
            $parse_area[$area['id']] = $area['name'];
        }

        $model = new Model("voucher");
        $where = "user_id = ".$this->user['id']." and is_send = 1";
        $where .= " and status = 0 and '".date("Y-m-d H:i:s")."' <=end_time";
        $voucher = $model->where($where)->order("id desc")->findAll();

        $this->assign("voucher",$voucher);
        $this->assign("open_invoice",$open_invoice);
        $this->assign("tax",$tax);
        $this->assign("address",$address);
        $this->assign("parse_area",$parse_area);
        $this->assign("order_status",Session::get("order_status"));
    }
    //打包团购订单商品信息
    private function packGroupbuyProducts($item,$num=1){
        $store_nums = $item['store_nums'];
        $have_num = $item['max_num']-$item['goods_num'];
        if($have_num>$store_nums) $have_num = $store_nums;
        if($num>$have_num) $num = $have_num;
        $amount = sprintf("%01.2f",$item['price']*$num);
        $sell_total = $item['sell_price']*$num;
        $product_id = $item['product_id'];

        $product[$product_id] = array('id'=>$product_id,'goods_id'=>$item['goods_id'],'name'=>$item['name'],'img'=>$item['img'],'num'=>$num,'store_nums'=>$have_num,'price'=>$item['price'],'spec'=>unserialize($item['spec']),'amount'=>$amount,'sell_total'=>$sell_total,'weight'=>$item['weight'],'point'=>$item['point'],"prom_goods"=>array(),"sell_price"=>$item['sell_price'],"real_price"=>$item['price']);
        return $product;
    }
    //打包抢购订单商品信息
    private function packFlashbuyProducts($item,$num=1){
        $store_nums = $item['store_nums'];
        $quota_num = $item['quota_num'];
        $have_num = $item['max_num']-$item['goods_num'];
        if($have_num>$store_nums) $have_num = $store_nums;
        if($have_num>$quota_num) $have_num = $quota_num;
        if($num>$have_num) $num = $have_num;
        $amount = sprintf("%01.2f",$item['price']*$num);
        $sell_total = $item['sell_price']*$num;
        $product_id = $item['product_id'];

        $product[$product_id] = array('id'=>$product_id,'goods_id'=>$item['goods_id'],'name'=>$item['name'],'img'=>$item['img'],'num'=>$num,'store_nums'=>$have_num,'price'=>$item['price'],'spec'=>unserialize($item['spec']),'amount'=>$amount,'sell_total'=>$sell_total,'weight'=>$item['weight'],'point'=>$item['point'],"prom_goods"=>array(),"sell_price"=>$item['sell_price'],"real_price"=>$item['price']);
        return $product;
    }
    //捆绑订单商品信息
    private function packBundbuyProducts($items,$num=1){
        $max_num = $num;
        foreach ($items as $prod) if($max_num>$prod['store_nums'])$max_num = $prod['store_nums'];
        $num = $max_num;
        foreach($items as $item) {
            $store_nums = $item['store_nums'];
            $amount = sprintf("%01.2f",$item['sell_price']*$num);
            $sell_total = $item['sell_price']*$num;
            $product_id = $item['product_id'];

            $product[$product_id] = array('id'=>$product_id,'goods_id'=>$item['goods_id'],'name'=>$item['name'],'img'=>$item['img'],'num'=>$num,'store_nums'=>$item['store_nums'],'price'=>$item['sell_price'],'spec'=>unserialize($item['spec']),'amount'=>$amount,'sell_total'=>$sell_total,'weight'=>$item['weight'],'point'=>$item['point'],"prom_goods"=>array(),"sell_price"=>$item['sell_price'],"real_price"=>$item['sell_price']);
        }
        return $product;
    }
    //非普通促销确认订单
    public function order_info(){
        $id = Filter::int(Req::args('id'));
        $product_id = Req::args('pid');
        $type = Req::args("type");
        if($this->checkOnline()){
            if($type=='groupbuy'){
            	$product_id = Filter::int($product_id);
                $model = new Model("groupbuy as gb");
                $item = $model->join("left join goods as go on gb.goods_id=go.id left join products as pr on pr.goods_id=gb.goods_id")->fields("*,pr.id as product_id,pr.store_nums")->where("gb.id=$id and pr.id=$product_id")->find();
                if($item){
                    $start_diff = time()-strtotime($item['start_time']);
                    $end_diff = time()-strtotime($item['end_time']);
                    if($item['is_end']==0 && $start_diff>=0 && $end_diff<0 && $item['store_nums']>0){
                        $product = $this->packGroupbuyProducts($item);
                        $this->assign("product",$product);
                    }else{
                        $this->redirect("/index/groupbuy/id/$id");
                    }
                }else{
                    Tiny::Msg($this,"你提交的团购不存在！",404);
                    exit;
                }
            }else if($type=='flashbuy'){
                $model = new Model("flash_sale as fb");
                $product_id = Filter::int($product_id);
                $item = $model->join("left join goods as go on fb.goods_id=go.id left join products as pr on pr.goods_id=fb.goods_id")->fields("*,pr.id as product_id,pr.store_nums")->where("fb.id=$id and pr.id=$product_id")->find();
                if($item){
                    $start_diff = time()-strtotime($item['start_time']);
                    $end_diff = time()-strtotime($item['end_time']);
                    if($item['is_end']==0 && $start_diff>=0 && $end_diff<0 && $item['store_nums']>0){
                        $product = $this->packFlashbuyProducts($item);
                        $this->assign("product",$product);
                    }else{
                        $this->redirect("/index/flashbuy/id/$id");
                    }
                }else{
                    Tiny::Msg($this,"你提交的抢购不存在！",404);
                    exit;
                }

            }else if($type == 'bundbuy'){
                //确认捆绑存在有效且所有的商品都在其中包括个数完全正确
                $product_id = trim($product_id,"-");
                $product_id_array = explode("-",$product_id);
                foreach($product_id_array as $key=>$val){
                	$product_id_array[$key] = Filter::int($val);
                }
                $product_ids = implode(',', $product_id_array);
                $product_id = implode('-', $product_id_array);
                $model = new Model("bundling");
                $bund = $model->where("id=$id")->find();
                if($bund){
                    $goods_id_array = explode(',',$bund['goods_id']);

                    $products = $model->table("goods as go")->join("left join products as pr on pr.goods_id=go.id")->where("pr.id in ($product_ids)")->fields("*,pr.id as product_id")->group("go.id")->findAll();
                    //检测库存与防偷梁换柱
                    foreach ($products as  $value) {
                        if($value['store_nums']<=0 || !in_array($value['goods_id'], $goods_id_array)){
                            $this->redirect("/index/bundbuy/id/$id");
                        }
                    }
                    if(count($goods_id_array)==count($products)){
                        $product = $this->packBundbuyProducts($products);
                        $this->assign("product",$product);
                        $this->assign("bund",$bund);
                    }else{
                        $this->redirect("/index/bundbuy/id/$id");
                    }
                    $product_id = $product_id;
                }
                else{
                   $this->redirect("/index/msg",true,array('msg'=>'你提交的套餐不存在！','type'=>'error'));
                }
            }
            $this->assign("id",$id);
            $this->assign("order_type",$type);
            $this->assign("pid",$product_id);
            $this->parserOrder();
            $this->redirect();
        }else{
            $this->redirect("login");
        }
    }
    //团购商品数量
    public function groupbuy_num(){
        $id = Filter::int(Req::args('id'));
        $num = Filter::int(Req::args('num'));
        $address_id = Filter::int(Req::args('address_id'));
        if($num<=0)$num = 1;
        $product_id = Filter::int(Req::args('pid'));
        $model = new Model("groupbuy as gb");
        $item = $model->join("left join goods as go on gb.goods_id=go.id left join products as pr on pr.id=$product_id")->fields("*,pr.id as product_id")->where("gb.id=$id")->find();
        $product = $this->packGroupbuyProducts($item,$num);
        $weight = $product[$product_id]['weight'] * $num;
        $fare = new Fare($weight);
        $fee = $fare->calculate($address_id);
        $product[$product_id]['freight'] = $fee;
        $product[$product_id]['totalWeight'] = $weight;
        echo JSON::encode($product);
    }
    //抢购商品数量
    public function flashbuy_num(){
        $id = Filter::int(Req::args('id'));
        $num = Filter::int(Req::args('num'));
        $address_id = Filter::int(Req::args('address_id'));
        if($num<=0)$num = 1;
        $product_id = Filter::int(Req::args('pid'));
        $model = new Model("flash_sale as fb");
        $item = $model->join("left join goods as go on fb.goods_id=go.id left join products as pr on pr.id=$product_id")->fields("*,pr.id as product_id")->where("fb.id=$id")->find();
        $product = $this->packFlashbuyProducts($item,$num);
        $weight = $product[$product_id]['weight'] * $num;
        $fare = new Fare($weight);
        $fee = $fare->calculate($address_id);
        $product[$product_id]['freight'] = $fee;
        $product[$product_id]['totalWeight'] = $weight;
        echo JSON::encode($product);
    }
    //捆绑商品数量
    public function bundbuy_num(){
        $id = Filter::int(Req::args('id'));
        $num = Filter::int(Req::args('num'));
        $address_id = Filter::int(Req::args('address_id'));
        if($num<=0)$num = 1;
        $product_id = Req::args('pid');
        $id_arrary = explode('-', $product_id);
        foreach ($id_arrary as $key => $value) {
            $id_arrary[$key] = Filter::int($value);
        }
        $product_ids = implode(',', $id_arrary);
        $model = new Model("bundling");
        $bund = $model->where("id=$id")->find();
        if($bund){
            $goods_id = $bund['goods_id'];
            $products = $model->table("goods as go")->join("left join products as pr on pr.goods_id=go.id")->where("pr.id in ($product_ids)")->fields("*,pr.id as product_id")->group("go.id")->findAll();
            $products = $this->packBundbuyProducts($products);
        }
        $weight = 0;
        $max_num = $num;
        foreach ($products as $prod) {
            $weight += $prod['weight'];
            if($max_num>$prod['store_nums'])$max_num = $prod['store_nums'];
        }
        $num = $max_num;
        $amount = sprintf("%01.2f",$bund['price'] * $num);
        $product[$product_id] = array('id'=>$product_ids,'goods_id'=>'','name'=>'','img'=>'','num'=>$num,'store_nums'=>$num,'price'=>$bund['price'],'spec'=>array(),'amount'=>$amount,'sell_total'=>$amount,'weight'=>$weight,'point'=>'',"prom_goods"=>array(),"sell_price"=>$bund['price'],"real_price"=>$bund['price']);

        $weight = $weight * $num;
        $fare = new Fare($weight);
        $fee = $fare->calculate($address_id);
        $product[$product_id]['freight'] = $fee;
        $product[$product_id]['totalWeight'] = $weight;

        echo JSON::encode($product);
    }
    
    
    
    
//根据商品数组对象得到商品总额等信息(自己写的)
	//创建多用户订单中的商品总额等信息
	protected  function getGoodsTotalMoneyByPNo($array_list)
	{
		$total = 0.00;//订单总金额
		$point = 0;//积分
		$xjq = 0;//现金券
		$seller_id=0;//商家id
		foreach($array_list as $key=>$value)
		{
			$total += $value['sell_price'] * $value['nums'];
        	//$cb += $value['cb'] * $value['nums'];
        	$point += $value['point'] * $value['nums'];
        	$seller_id = $value['seller_id'];//给商家id赋值
        	//$xjq += $value['xjq'];//现金券
		}
		
		$ship_money = Common::getConfigValue("ship_money");
		if($cb < 100)
		{
			$total += $ship_money;
		}
		
		$data['seller_id'] = $seller_id;
        $data['total'] = sprintf("%.2f", $total);//订单总金额
        //$data['cb'] = $cb;//订单总彩币
        $data['point'] = $point;//订单总积分
        //$data['xjq'] = $xjq;//现金券
        return $data;
	}
	
	
	//生成订单  (多用户订单)(自己写的)
	protected  function create_new_order($userId,$payment_id, $addrId, $intro, $array_list)
	{
		
		$model = new Model();
		//订单号
		$data['order_no'] = Common::createOrderNo();
		$data['payment'] = $payment_id;
		//用户id
		$data['user_id'] = $userId;
		
		$addressObj = Common::getAreaObjById($addrId);
		//省
		$data['province'] = $addressObj['province'];
		//市
		$data['city'] = $addressObj['city'];
		//县
		$data['county'] = $addressObj['county'];
		//邮政编码
		$data['zip'] = $addressObj['zip'];
		//简单地址
		$data['addr'] = $addressObj['addr'];
		//收货姓名
		$data['accept_name'] = $addressObj['accept_name'];
		$data['phone'] = $addressObj['phone'];
		$data['mobile'] = $addressObj['mobile'];
		//创建时间
		$data['create_time'] = date('Y-m-d H:i:s',time());
		//用户订单备注
		$data['user_remark'] = $intro;
		
		$data['status'] = 2;//待审核
		
        $data['pay_status'] = 0;//未付款
        
        
        $info = self::getGoodsTotalMoneyByPNo($array_list);
        
        //商家id
        $data['seller_id'] = $info['seller_id'];
        
        //应付商品总额
        $data['payable_amount'] = $info['total'];
        //实付商品总额
        $data['real_amount'] = $info['total'];
		//调整后的商品总额
        $data['order_amount'] = $info['total'];
		//订单中的彩币总和
        //$data['hjcb'] = $info['cb'];
        //订单中的xjq
        //$data['xjq'] = $info['xjq'];
        
//        $ship_money = Common::getConfigValue("ship_money");
//        if($info['cb'] < 100)
//        {
//        	$data['post_money'] = $ship_money;
//        }
        
        //订单积分    
        $data['point'] = $info['point'];
            
        //配送费用
        $data['payable_freight'] = 0.00;
		//实际配送费用
        $data['real_freight'] = 0.00;
        //订单类型(0普通订单 1团购订单 2限时抢购 3捆绑促销)
        $data['type'] = 0;
        //优惠券id
        $data['voucher_id'] = 0;
        //优惠券信息
        $data['voucher'] = serialize(array());
        
        //店铺自取时，店铺类型
        //$data['delivery_dp_id'] = $dp_id;
        //写入订单数据
        $order_id = $model->table("order")->data($data)->insert();
        
        //写入订单商品
        $tem_data = array();
        //如果订单中包含多商户商品
        foreach($array_list as $key=>$v)
		{	
			$tem_data['order_id'] = $order_id;
            $tem_data['goods_id'] = $v['goods_id'];//单个商品id
            $tem_data['product_id'] = $v['id'];//单个商品货号
            $tem_data['goods_price'] = $v['sell_price'];//单个商品零售价
            $tem_data['real_price'] = $v['sell_price'];
            //$tem_data['p_cb'] = $v['cb'];//单个商品彩币
            $tem_data['goods_nums'] = $v['nums'];//购买的商品数量
            $tem_data['goods_weight'] = $v['weight'];//商品重量
            
            $tem_data['prom_goods'] = serialize(array('real_price'=>$v['sell_price'],'note'=>'','minus'=>'-0'));
            $tem_data['spec'] = serialize($v['spec']);
           
            $model->table("order_goods")->data($tem_data)->insert();
            
		}
		
		$child_order_obj = array();
		$child_order_obj['order_no'] = $data['order_no'];//保存子订单号
		$child_order_obj['order_amount'] = $info['total'];//保存子订单金额
		$child_order_obj['seller_id'] = $v['seller_id'];
		
		//$child_order_obj['cb'] = $info['cb'];
		
		return $child_order_obj;
	}
    
    
    
    
	/**
     * 检测一个订单是否为合并订单(自己写的)
     * 满足条件：订单中必须商品种类必须大于1，且其中必须有1个以上的商家
     * Enter description here ...
     * @param unknown_type $arrayList
     */
    protected  function checkIsHeBingOrder($arrayList=null)
    {
    	$model = new Model();
    	$arr=array();
    	foreach($arrayList as $key=>$value)
    	{
    		$seller_id = $model->table("goods")->where("id=".$value['goods_id'])->find()['seller_id'];
    		$arr[$seller_id] =0;
    		
    	}
    	
    	if(count($arr) > 1)return 1;
    	else return 0;
    }
    
    //提交订单处理
    public function order_act()
    {
        if($this->checkOnline()){
//        if(1==1){
            $address_id = Filter::int(Req::args('address_id'));
            $payment_id = Filter::int(Req::args('payment_id'));
            $prom_id = Filter::int(Req::args('prom_id'));
            $is_invoice = Filter::int(Req::args('is_invoice'));
            $invoice_type = Filter::int(Req::args('invoice_type'));
            $invoice_title = Filter::text(Req::args('invoice_title'));
            $user_remark = Filter::txt(Req::args('user_remark'));
            $voucher_id = Filter::int(Req::args('voucher'));
            $cart_type = Req::args('cart_type');
			
            
            //非普通促销信息
            $type = Req::args("type");
            $id = Filter::int(Req::args('id'));
            $product_id = Req::args('product_id');
            $buy_num = Req::args('buy_num');
            
            
            //抵消金额
            $dx_je = Req::args("dx_je");
            if(empty($dx_je))
            {
                $dx_je = 0;
            }
            if(!Validator::float($dx_je))
            {
                $data['msg'] = array('fail',"抵消金额必须为数字！");
                $this->redirect("order",false,$data);
                exit;
            }
            
            

            if(!$address_id || !$payment_id || ($is_invoice==1 && $invoice_title=='')){
                if(is_array($product_id)){
                    foreach($product_id as $key=>$val){
                        $product_id[$key] = Filter::int($val);
                    }
                    $product_id = implode('-', $product_id);
                }
                else $product_id =  Filter::int($product_id);
                $data = Req::args();
                $data['is_invoice']=$is_invoice;
                if(!$address_id) $data['msg'] = array('fail',"必需选择收货地址，才能确认订单。");
                else if(!$payment_id)$data['msg'] = array('fail',"必需选择支付方式，才能确认订单。");
                else $data['msg'] = array('fail',"索要发票，必需写明发票抬头。");
                if($type==null)$this->redirect("order",false,$data);
                else {
                    unset($data['act']);
                    Req::args('pid',$product_id);
                    Req::args('id',$id);
                    unset($_GET['act']);
                    Req::args('type',$type);
                    Req::args('msg',$data['msg']);
                    $this->redirect("/simple/order_info",true,Req::args());
                }
                exit;
            }
            
            
            //地址信息
            $address_model = new Model('address');
            $address = $address_model->where("id=$address_id and user_id=".$this->user['id'])->find();
            
            if(!$address){
                $data = Req::args();
                $data['msg'] = array('fail',"选择的地址信息不正确！");
                $this->redirect("order",false,$data);
                exit;
            }
            
            
            $user_obj = Common::get_user_obj($this->user['id']);
            $xjb = $user_obj['xjf'];
            if($dx_je < $xjb)
            {
                $data['msg'] = array('fail',"抵消金额超过现金分账户余额！");
                $this->redirect("order",false,$data);
                exit;
            }
            
            
            //if(!$payment_id)$this->redirect("order",false,Req::args());
			
            if($this->getModule()->checkToken('order')){
			//if(1==1){	
            	
				
                //订单类型: 0普通订单 1团购订单 2限时抢购 3捆绑促销
                $order_type = 0;
                $model = new Model('');

                //团购处理
                if($type=="groupbuy"){
                    $product_id = Filter::int($product_id[0]);
                    $num = Filter::int($buy_num[0]);
                    if($num<1) $num = 1;
                    $item = $model->table("groupbuy as gb")->join("left join goods as go on gb.goods_id=go.id left join products as pr on pr.id=$product_id")->fields("*,pr.id as product_id,pr.spec")->where("gb.id=$id")->find();
                    $order_products = $this->packGroupbuyProducts($item,$num);

                    $groupbuy = $model->table("groupbuy")->where("id=$id")->find();
                    unset($groupbuy['description']);
                    $data['prom'] = serialize($groupbuy);
                    $data['prom_id'] = $id;
                    $order_type = 1;

                }else if($type=="flashbuy"){//抢购处理
                    $product_id = Filter::int($product_id[0]);
                    $num = Filter::int($buy_num[0]);
                    if($num<1) $num = 1;
                    $item = $model->table("flash_sale as fb")->join("left join goods as go on fb.goods_id=go.id left join products as pr on pr.id=$product_id")->fields("*,pr.id as product_id,pr.spec")->where("fb.id=$id")->find();
                    $order_products = $this->packFlashbuyProducts($item,$num);

                    $flashbuy = $model->table("flash_sale")->where("id=$id")->find();
                    unset($flashbuy['description']);
                    $data['prom'] = serialize($flashbuy);
                    $data['prom_id'] = $id;
                    $order_type = 2;
                }else if($type=="bundbuy"){//捆绑销售处理
                    if(is_array($product_id)){
                        foreach($product_id as $key=>$val){
                            $product_id[$key] = Filter::int($val);
                        }
                    }
                    else $product_id =  Filter::int($product_id);

                    $product_ids = implode(',', $product_id);
                    $num = Filter::int($buy_num[0]);

                    $model = new Model("bundling");
                    $bund = $model->where("id=$id")->find();

                    if($bund){
                        $goods_id = $bund['goods_id'];
                        $products = $model->table("goods as go")->join("left join products as pr on pr.goods_id=go.id")->where("pr.id in ($product_ids)")->fields("*,pr.id as product_id,pr.spec")->group("go.id")->findAll();
                        $order_products = $this->packBundbuyProducts($products,$num);
                    }

                    $bundbuy = $model->table("bundling")->where("id=$id")->find();
                    unset($bundbuy['description']);
                    $data['prom'] = serialize($bundbuy);
                    $data['prom_id'] = $id;
                    $current = current($order_products);
                    $bundbuy_amount = sprintf("%01.2f",$bund['price']) * $current['num'];

                    $order_type = 3;
                }
                if($order_type==0){

                    if($cart_type == 'goods'){
                        $cart = Cart::getCart('goods');
                    }else{
                        $cart = Cart::getCart();
                    }
                    $order_products = $cart->all();
                    $data['prom_id'] = $prom_id;
                }

                //检测products 是否还有数据
                if(empty($order_products)){
                    $msg = array('type'=>'fail','msg'=>'非法提交订单！');
                    $this->redirect('/index/msg',false,$msg);
                    return;
                }
                
                //检查商品是否属于同一个类别
                if( !Common::check_goods_list_is_one_category($order_products))
                {
                    //$msg = array('type'=>'fail','msg'=>"有不同支付方式的商品存在，请分批次购买！<a style='color:red;' href='javascript:window.history.go(-1);'>返回</a>");
                    $msg = array('type'=>'fail','msg'=>"有不同支付方式的商品存在，请分批次购买！");
                    $this->redirect('/index/msg',false,$msg);
                    return;
                }
                
                //得到订单的支付类型
                
                $o_pay_id = Common::get_order_payment_id($order_products);
                //echo $payment_id." ".$o_pay_id;die;
                if($o_pay_id !== intval($payment_id))
                {
                    $data = Req::args();
                    $data['msg'] = array('fail',"请选择另一种支付方式！");
                    $this->redirect("order",false,$data);
                    exit;
                }
                
                
				
                
            	//自己加的
                //判断该订单是否为合并订单
                if(self::checkIsHeBingOrder($order_products))
                {
                	sort($order_products);
                	
                	//如果该订单为合并订单，则
                	foreach($order_products as  $key=>$value)
                	{
                		$goodsObj=$model->table("goods")->where("id=".$value['goods_id'])->find();
                		
                		//$value['seller_id'] = $goodsObj['seller_id'];//商品所有者
                		//$value['point'] = $goodsObj['point']; //商品积分
                		$order_products[$key]['nums'] = $value['num'];
                		$order_products[$key]['sell_price'] = $value['price'];
                		$order_products[$key]['spec'] = $value['spec'];
                		$order_products[$key]['seller_id'] = $goodsObj['seller_id'];//商品所有者
                		$order_products[$key]['point'] = $goodsObj['point']; //商品积分
                		//$order_products[$key]['xjq'] = $goodsObj['xjq']; //现金券
                	}
                	
                	$demoList=array();
                	
                	for($i=0; $i<count($order_products); $i++)
                	{
                		$productObj = $model->table("products")->fields("seller_id")->where("id=".$order_products[$i]['id'])->find();
                		$demoList[$productObj['seller_id']][$i]=$order_products[$i];
                	}
                	
                	$child_order_list=array();
                	
                	foreach($demoList as  $value)
                	{
                		//(如果存在多商家)循环生成订单,并得到子订单返回信息
                		//dp_id 店铺自取时店铺id
						$child_order_list[] = self::create_new_order($this->user['id'],$payment_id, $address_id, $user_remark, $value);
                	}
                	
                	
                	
                	$cc=0;
                	//将n个子订单和一个合并订单信息添加到合并订单表中
					for($i=0; $i<count($child_order_list); $i++)
					{
						$order_no        = "HB".Common::createOrderNo();//订单号(重新生成新的订单号)
						$child_order_no .= $child_order_list[$i]['order_no'].",";
						$seller_id      .= $child_order_list[$i]['seller_id'].",";//所属商户id
						$order_amount   += $child_order_list[$i]['order_amount'];//订单金额
						$remark         .= "包含子订单".$child_order_list[$i]['order_no']." ";//订单备注
						
						//$total_cb += $child_order_list[$i]['cb'];//合并订单的总彩币
						
//						if(intval($child_order_list[$i]['cb']) < 100)
//						{
//							$cc++;
//						}
						
					}
					
					
                	//税计算
	                $tax_fee = 0;
	                $config = Config::getInstance();
	                $config_other = $config->get('other');
	                $open_invoice = isset($config_other['other_is_invoice'])?!!$config_other['other_is_invoice']:false;
	                $tax = isset($config_other['other_tax'])?intval($config_other['other_tax']):0;
	                if($open_invoice && $is_invoice){
	                    $tax_fee = $real_amount*$tax/100;
	                }
	                
					
	                //计算合并订单的总运费
	                //$ship_money = Common::getConfigValue("ship_money");
	                
	                $t = 0;
	                
//                	for($i=0; $i<$cc; $i++)
//                	{
//                		$t += $ship_money;
//                	}
//	               
//	                if($total_cb < 100)
//	                {
//	                	$demo['post_money'] = $t;
//	                }
	                
					$demo['order_no']       = $order_no;
					$demo['child_order_no'] = trim($child_order_no, ",");//该订单的子订单号连接 比如a,b
					$demo['seller_id']      = trim($seller_id, ",");//该订单所属的商家id连接 比如a,b
					$demo['order_amount']   = $order_amount - $t + $tax_fee;
					$demo['remark']         = $remark;
					$demo['create_time']    = date("Y-m-d H:i:s", time());
					$demo['user_id']        = $this->user['id'];//该订单购买者的id
					
					
					//将合并订单数据保存到合并订单表中
					$model->table("demo_order")->data($demo)->insert();
					//返回合并订单表中的最后插入的订单id
					//$demo = $model->query("select last_insert_id() as 'order_id'");
					//$order_id = $demo['order_id'];
               		//清空购物车与表单缓存
	                if($order_type==0){
	                    $cart = Cart::getCart();
	                    $cart->clear();
	                    Session::clear("order_status");
	                }
	                $payment = new Payment($payment_id);
	                $payment_plugin = $payment->getPaymentPlugin();
	                if($payment_plugin->isOnlinePay()){
	                	$demo = $model->query("select max(id) as 'order_id' from zyk_demo_order");
	                	$order_id = $demo[0]['order_id'];
	                	
	                    $this->redirect("/simple/hebing_order_status/order_id/{$order_id}");
	                }else{
	                    $this->redirect("/simple/hebing_order_completed/order_id/{$order_id}");
	                }
                	
                	
                	
                }
                else 
                {
	                //商品总金额,重量,积分计算
	                $payable_amount = 0.00;
	                $real_amount = 0.00;
	                $weight=0;
	                $point = 0;
	                foreach ($order_products as $item) {
	                    $payable_amount+=$item['sell_total'];
	                    $real_amount+=$item['amount'];
	                    $weight += $item['weight']*$item['num'];
	                    $point += $item['point']*$item['num'];
                        $seller_id = Common::getGoodsInfo($item['goods_id'])['seller_id'];//写入商品所属店铺id
	                }
	                if($order_type == 3) $real_amount = $bundbuy_amount;
	
	                //计算运费
	                $fare = new Fare($weight);
	                //$payable_freight = $fare->calculate($address_id);
	                //运费暂时改为0
	                $payable_freight = 0;
	                //$real_freight = $payable_freight;
	                $real_freight = 0;
	                
	
	                //计算订单优惠
	                $prom_order = array();
	                $discount_amount = 0;
	                if($order_type ==0 ){
	                    if($prom_id){
	                        $prom = new Prom($real_amount);
	                        $prom_order = $model->table("prom_order")->where("id=$prom_id")->find();
	
	                        //防止非法会员使用订单优惠
	                        $user = $this->user;
	                        $group_id = ',0,';
	                        if(isset($user['group_id'])) $group_id = ','.$user['group_id'].',';
	
	                        if(stripos(','.$prom_order['group'].',',$group_id)!==false){
	                            $prom_parse = $prom->parsePorm($prom_order);
	                            $discount_amount = $prom_parse['value'];
	                            if($prom_order['type']==4) $discount_amount = $payable_freight;
	                            else if($prom_order['type']==2){
	                                $multiple = intval($prom_order['expression']);
	                                $multiple = $multiple==0?1:$multiple;
	                                $point = $point * $multiple;
	                            }
	                            $data['prom'] = serialize($prom_order);
	                        }
	                        else $data['prom'] = serialize(array());
	                    }
	                }
	                //税计算
	                $tax_fee = 0;
	                $config = Config::getInstance();
	                $config_other = $config->get('other');
	                $open_invoice = isset($config_other['other_is_invoice'])?!!$config_other['other_is_invoice']:false;
	                $tax = isset($config_other['other_tax'])?intval($config_other['other_tax']):0;
	                if($open_invoice && $is_invoice){
	                    $tax_fee = $real_amount*$tax/100;
	                }
	
	                //代金券处理
	                $voucher_value = 0;
	                $voucher = array();
	                if($voucher_id){
	                    $voucher = $model->table("voucher")->where("id=$voucher_id and is_send=1 and user_id=".$this->user['id']." and status = 0 and '".date("Y-m-d H:i:s")."' <=end_time and '".date("Y-m-d H:i:s")."' >=start_time and money<=".$real_amount)->find();
	                    if($voucher){
	                        $voucher_value = $voucher['value'];
	                        if($voucher_value>$real_amount)$voucher_value = $real_amount;
	                    }
	                }
	                //计算订单总金额
	                $order_amount = $real_amount + $payable_freight + $tax_fee - $discount_amount - $voucher_value;
	
	                //现金币账户减去抵消金额
	                $model->table("customer")->data(['xjf'=>"`xjf`-$dx_je"])->where("user_id=".$user_obj['id'])->update();
	
	                //填写订单
	                $data['order_no'] = Common::createOrderNo();
                    $data['user_id'] = $this->user['id'];
	                $data['seller_id'] = $seller_id;//写入商品所属店铺id
	                $data['payment'] = $payment_id;
	                $data['status'] = 2;
	                $data['pay_status'] = 0;
	                $data['accept_name'] = Filter::text($address['accept_name']);
	                $data['phone'] = $address['phone'];
	                $data['mobile'] = $address['mobile'];
	                $data['province'] = $address['province'];
	                $data['city'] = $address['city'];
	                $data['county'] = $address['county'];
	                $data['addr'] = Filter::text($address['addr']);
	                $data['zip'] = $address['zip'];
	                $data['payable_amount'] = $payable_amount;
	
	                $data['payable_freight'] = $payable_freight;
	                $data['real_freight'] = $real_freight;
	                $data['create_time'] = date('Y-m-d H:i:s');
	                $data['user_remark'] = $user_remark;
	                $data['is_invoice'] = $is_invoice;
	                if($is_invoice==1){
	                    $data['invoice_title'] = $invoice_type.':'.$invoice_title;
	                }else{
	                    $data['invoice_title'] = '';
	                }
	
	                $data['taxes'] = $tax_fee;
	
	
	                $data['discount_amount'] = $discount_amount-$dx_je;
	
	                $data['order_amount'] = $order_amount-$dx_je;
	                $data['real_amount'] = $real_amount-$dx_je;
	
	                $data['point'] = $point;
	                $data['type'] = $order_type;
	                $data['voucher_id'] = $voucher_id;
	                $data['voucher'] = serialize($voucher);
	
	
	                //写入订单数据
	                $order_id = $model->table("order")->data($data)->insert();
	                //写入订单商品
	                $tem_data = array();
	
	                foreach ($order_products as $item) {
	                    $tem_data['order_id'] = $order_id;
	                    $tem_data['dp_id'] = Common::getGoodsInfo($item['goods_id'])['u_dp_id'];//写入商品所属店铺id
	                    $tem_data['goods_id'] = $item['goods_id'];
	                    $tem_data['product_id'] = $item['id'];
	                    $tem_data['goods_price'] = $item['sell_price'];
	                    $tem_data['real_price'] = $item['real_price'];
	                    $tem_data['goods_nums'] = $item['num'];
	                    $tem_data['goods_weight'] = $item['weight'];
	                    $tem_data['prom_goods'] = serialize($item['prom_goods']);
	                    $tem_data['spec'] = serialize($item['spec']);
	                    $model->table("order_goods")->data($tem_data)->insert();
	                }
	                //发送提醒
	                // $NoticeService = new NoticeService();
	                // $data['user'] = $this->user['name'];
	                // $NoticeService->send('create_order',$data);
	                //优惠券锁死
	                /*
	                if(!empty($voucher)){
	                    $model->table("voucher")->where("id=$voucher_id and user_id=".$this->user['id'])->data(array('status'=>2))->update();
	                }
	                */
	                //清空购物车与表单缓存
	                if($order_type==0){
	                    $cart->clear();
	                    Session::clear("order_status");
	                }
	                
	                $this->redirect("/simple/order_completed/order_id/$order_id");
	                /*
	                $payment = new Payment($payment_id);
	                $payment_plugin = $payment->getPaymentPlugin();
	                if($payment_plugin->isOnlinePay()){
	                    $this->redirect("/simple/order_status/order_id/$order_id");
	                }else{
	                    $this->redirect("/simple/order_completed/order_id/$order_id");
	                }
	                */
	                
            	}
            	
            }
            else{
                $msg = array('type'=>'fail','msg'=>'非法提交订单！');
                $this->redirect('/index/msg',false,$msg);
            }
        }else{
            $this->redirect("login");
        }
    }
    
    
    public function order_status(){
    	
        if($this->checkOnline()){
            $order_id = Filter::int(Req::get("order_id"));
            if($order_id){
                $order = $this->model->table("order as od")->join("left join payment as pa on od.payment= pa.id")->fields("od.id,od.order_no,od.payment,od.pay_status,od.order_amount,od.point,pa.pay_name as payname,od.type,od.status")->where("od.id=$order_id and od.status<4 and od.user_id = ".$this->user['id'])->find();
                if($order){
                    if($order['pay_status']==0){
                        $payment_plugin = Common::getPaymentInfo($order['payment']);
                        if($payment_plugin!=null && $payment_plugin['class_name']=='received' && $order['status']==3){
                            $this->redirect("/simple/order_completed/order_id/$order_id");
                        }
                        $this->assign("order",$order);
                        $this->assign("zf_gwb",(Common::getConfigJjsetValue("jjset_zf_gwb")/100)*$order['order_amount']);
                        $this->assign("zf_xjb",(Common::getConfigJjsetValue("jjset_zf_balance")/100)*$order['order_amount']);
                        $this->redirect();
                    }else if($order['pay_status']==1){
                        $this->redirect("/simple/order_completed/order_id/$order_id");
                    }
                }else{
                    Tiny::Msg($this,404);
                }
            }else{
                Tiny::Msg($this,404);
            }
        }else{
            $this->redirect("login");
        }
    }
    
    public function order_completed(){
        if($this->checkOnline()){
            $order_id = Filter::int(Req::args("order_id"));
            if($order_id){
                $order = $this->model->table("order as od")->join("left join payment as pa on od.payment= pa.id")->fields("od.id,od.order_no,od.payment,od.pay_status,od.order_amount,pa.pay_name as payname,od.type,od.status")->where("od.id=$order_id and od.status<4 and od.user_id = ".$this->user['id'])->find();
                if($order){
                    if($order['pay_status']==1){
                        $this->assign("order",$order);
                        $this->redirect();
                    }else if($order['pay_status']==0){
                        $payment_plugin = Common::getPaymentInfo($order['payment']);
                        if($payment_plugin!=null && $payment_plugin['class_name']=='received'){
                            $this->assign("payment_type","received");
                            $this->assign("order",$order);
                            $this->redirect();
                        }else{
                            $this->redirect("/simple/order_status/order_id/$order_id");
                        }
                    }
                }else{
                    Tiny::Msg($this,404);
                }
            }else{
                Tiny::Msg($this,404);
            }
        }else{
            $this->redirect("login");
        }
    }
    public function get_voucher(){
        $page = Filter::int(Req::args("page"));
        $amount = Filter::int(Req::args("amount"));
        $where = "user_id = ".$this->user['id']." and is_send = 1";
        $where .= " and status = 0 and '".date("Y-m-d H:i:s")."' <=end_time and '".date("Y-m-d H:i:s")."' >=start_time and money<=".$amount;
        $voucher = $this->model->table("voucher")->where($where)->order("end_time")->findPage($page,10,1,true);
        $data = $voucher['data'];
        $voucher['data'] = $data;
        $voucher['status'] = "success";
        echo JSON::encode($voucher);
    }
    public function reg_result(){
        $this->assign("user",$this->user);
        $this->redirect();
    }
    public function address_other(){
        Session::set("order_status",Req::args());
        $this->layout = '';
        $id = Filter::int(Req::args("id"));
        if($id){
            $model = new Model("address");
            $data = $model->where("id = $id and user_id =".$this->user['id'])->find();
            $this->redirect("address_other",false,$data);
        }
        else $this->redirect();
    }
    public function address_from_ucenter(){
        $this->address_save("/ucenter/address");
    }
    public function address_save($redirect=null){
        $rules = array('zip:zip:邮政编码格式不正确!','addr:required:内容不能为空！','accept_name:required:收货人姓名不能为空!,mobile:mobi:手机格式不正确!,phone:phone:电话格式不正确','province:[1-9]\d*:选择地区必需完成','city:[1-9]\d*:选择地区必需完成','county:[1-9]\d*:选择地区必需完成');
        $info = Validator::check($rules);

        if(!is_array($info) && $info==true) {
            Filter::form(array('sql'=>'accept_name|mobile|phone','txt'=>'addr','int'=>'province|city|county|zip|is_default|id'));
            $is_default = Filter::int(Req::args("is_default"));
            if($is_default == 1){
                $this->model->table("address")->where("user_id=".$this->user['id'])->data(array('is_default'=>0))->update();
            }else{
                Req::args("is_default","0");
            }

            Req::args("user_id",$this->user['id']);
            $id = Filter::int(Req::args('id'));
            if($id){
                $this->model->table("address")->where("id=$id and user_id=".$this->user['id'])->update();
            }
            else{
                $obj = $this->model->table("address")->where('user_id='.$this->user['id'])->fields("count(*) as total")->find();
                if($obj && $obj['total']>=20){
                    $this->assign("msg",array("error",'地址最大允许添加20个'));
                    $this->redirect("address_other",false,Req::args());
                    exit();
                }else{
                    $address_id = $this->model->table("address")->insert();
                    $order_status = Session::get("order_status");
                    $order_status['address_id'] = $address_id;
                    Session::set("order_status",$order_status);
                }
            }

            $this->assign("msg",array("success","地址编辑成功!"));
            Req::args("id",null);
            //$this->redirect("address_other",false);

            if($redirect==null) echo "<script>parent.location.reload();</script>";
            else $this->redirect($redirect);
            exit;
        }
        else{
            $this->assign("msg",array("error",$info['msg']));
            $this->redirect("address_other",false,Req::args());
        }
    }
    //生成二维码
    public function qrcode(){
        $url = urldecode(Req::args("data"));
        QRcode::png($url,false,3);
    }
    
    public function logout()
    {
        $this->safebox->clear('user');
        $cookie = new Cookie();
        $cookie->setSafeCode(Tiny::app()->getSafeCode());
        $cookie->set('autologin',null,0);
        $this->redirect('/index/index');
    }
    
    //检测用户是否在线
    private function checkOnline(){
        if(isset($this->user)&& $this->user['name']!=null)
            return true;
        else return false;
    }
    
    
    
    
    
 //根据合并订单号获取其中的统计信息
    protected function getTotalInfo($oid)
    {
    	$model = new Model();
    	$info=array();
    	$child_orderno_str=$model->table("demo_order")->where("id=$oid")->find()["child_order_no"];
    	$arr=explode(",", $child_orderno_str);
    	$cb = 0;
    	$payment_id=0;
    	for($i=0;$i<count($arr); $i++)
    	{
    		$orderObj = $model->table("order")->where("order_no='{$arr[$i]}'")->find();
    		$cb += $orderObj['hjcb'];
    		$payment_id = $orderObj['payment'];
    	}
    	$info['hjcb']=$cb;
    	$info['payment'] = $payment_id;
    	return $info;
    }
    
    
	//自己写的(合并订单状态处理)
    public function hebing_order_status()
    {
	    if($this->checkOnline()){
	            $order_id = Filter::int(Req::get("order_id"));
	            
	            if($order_id){
	                //$order = $this->model->table("order as od")->join("left join payment as pa on od.payment= pa.id")->fields("od.id,od.order_no,od.payment,od.pay_status,od.hjcb,od.order_amount,pa.pay_name as payname,od.type,od.status")->where("od.id=$order_id and od.status<4 and od.user_id = ".$this->user['id'])->find();
	                $order = $this->model->table("demo_order")->where("id={$order_id} and user_id=".$this->user['id'])->find();
	            	if($order){
	                    //if($order['pay_status']==0){
	            		if($order['status']==0){
//	                        $payment_plugin = Common::getPaymentInfo($order['payment']);
//	                        if($payment_plugin!=null && $payment_plugin['class_name']=='received' && $order['status']==3){
//	                            $this->redirect("/simple/order_completed/order_id/$order_id");
//	                        }
							$info = self::getTotalInfo($order_id);
							//$order['hjcb'] = $info['hjcb'];
							$order['payment'] = $info['payment'];
							$this->assign("zf_gwb",(Common::getConfigJjsetValue("jjset_zf_gwb")/100)*$order['order_amount']);
                        	$this->assign("zf_xjb",(Common::getConfigJjsetValue("jjset_zf_balance")/100)*$order['order_amount']);
	                        $this->assign("order",$order);
	                        $this->redirect();
	                    //}else if($order['pay_status']==1){
	                    }else if($order['status']==1){
	                        $this->redirect("/simple/hebing_order_completed/order_id/$order_id");
	                    }
	                }else{
	                    Tiny::Msg($this,404);
	                }
	            }else{
	                Tiny::Msg($this,404);
	            }
	        }else{
	            $this->redirect("login");
	        }
    }
    
    
    
//----------------------自己写的------合并订单支付结果详情页面-----------------------
    public function hebing_order_completed()
    {
    	if($this->checkOnline())
    	{
    		$order_id = Filter::int(Req::args("order_id"));
    		if($order_id)
    		{
    			$order = $this->model->table("demo_order")->where("id=".$order_id)->find();
    			if($order)
    			{
    				$child_order_list=explode(",",$order['child_order_no']);
    				$hjcb=0;
    				for($i=0;$i<count($child_order_list);$i++)
    				{
    					$demo =$this->model->table("order")->where("order_no='{$child_order_list[$i]}'")->find();
    					$arr[$i]["id"]=$demo['id'];
    					$arr[$i]['type'] = $demo['type'];
    					$arr[$i]['order_no']=$child_order_list[$i];
    					$hjcb += $demo['hjcb'];//七彩币计算
    					$arr[$i]['point'] = $demo['point'];//合计订单积分
    				}
    				$order['hjcb'] = $hjcb;
    				$this->assign("arr", $arr);
    				$this->assign("order", $order);
    				$this->redirect();
    				
    			}
    			else 
    			{
    				Tiny::Msg($this,404);
    			}
    		}
    		else
    		{
    			Tiny::Msg($this,404);
    		}
    	}
    	else 
    	{
    		$this->redirect("login");
    	}
    }
    
    /**
     * 每天自动返现
     * 百度bcm每天每隔15分访问一次该代码
     */
    public function auto_sf_point()
    {
        Jjjs::AllDayFhjjs();
    }
    
    
    //根据url生成二维码图片
    function get_qrcode_img_by_url()
    {
        $url = Req::args('url');
        require APP_ROOT.'/protected/classes/phpqrcode/phpqrcode.php';
        //$value="http://www.useryx.com";
        $errorCorrectionLevel = "L"; // 纠错级别：L、M、Q、H
        $matrixPointSize = "4"; // 点的大小：1到10
        QRcode::png($url, false, $errorCorrectionLevel, $matrixPointSize);
         
    }
    
    
    //获取新版本
    public function get_new_version()
    {
        
        $version_code = intval( Req::args("Version") );//这个是version_code
        
        if( !empty($version_code) )
        {
            $model = new Model("version");
             
            $result = $model->query("select max(version_code) as max_version_code from zyk_version");
            $maxVersionCode = intval( $result[0]['max_version_code'] );
            
            if($maxVersionCode !== $version_code)
            {
                $o = $model->where("version_code=".$maxVersionCode)->find();
                $data['Intro']=$o['introduct'];
                $data['VersionCode']=$o['version_code'];
                $data['VersionName']=$o['version_no'];
                $data['ReleaseDate']=$o['crete_time'];
                if( intval( $o['now_update']) === 0)
                {
                    $data['NowUpdate']=1;
                }
                else
                {
                    $data['NowUpdate']=0;
                }
                /*
                $config = Config::getInstance();
                $domain = $config->get('domain');
                */
                //$data['Url'] = $domain.$o['url'];
                $data['Url'] = Url::getHost().$o['url'];
                $data['Msg'] = "获取新版本成功";
                $data['Result'] = 0;
                echo Json::_toJSON($data);
                die;
            }
            else
            {
                $data['Msg'] = "暂时无版本更新";
                $data['Result'] = 1;
                echo Json::_toJSON($data);
                die;
            }
        }
    }
    
    
    public function download()
    {
        $version_model = new Model();
        $sql="select * from zyk_version where version_code=(select max(version_code) from zyk_version)";
        $result=$version_model->query($sql);
        if(!empty($result))
        {
            $config = Config::getInstance();
            $domain=$config->get("domain");
            $url=$domain.$result[0]['url'];
            echo "<script>document.location.href='{$url}';</script>";
        }
        else
        {
            echo "<script>alert('目前还没有APP版本发布');</script>";
        }
        die;
    
    }


    /**
     * 区域
     */
    public function transform()
    {
        $id = Req::args("id");
        $arr_city = $this->model->table("area") ->where("parent_id = ".$id)->select();
        $str = '';
        for($i=0; $i<count($arr_city); $i++)
        {
            $id = $arr_city[$i]['id'];
            $str .= "<option value='{$id}'>{$arr_city[$i]['name']}</option>";
        }

        echo $str;
    }
    
    
    
}
